package com.sfx.算法专题.链表.删除链表;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-08-01
 * Time: 23:19
 */
public class Code_5_deleteDuplicates {
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    /**
     * 单指针
     */
    static class Solution1 {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode dummy = new ListNode(-1);
            dummy.next = head;
            ListNode cur = dummy;
            while(cur.next!=null && cur.next.next!=null) {
                if(cur.next.val == cur.next.next.val) {
                    int x = cur.next.val;
                    //把等于x的节点全部删除
                    while(cur.next!=null&&cur.next.val == x) {
                        cur.next = cur.next.next;
                    }
                }else {
                    cur = cur.next;
                }
            }
            return dummy.next;
        }
    }

    /**
     * 双指针
     */
    static class Solution2 {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode dummy = new ListNode(-1);
            ListNode prev = dummy;
            ListNode cur = head;
            while (cur != null) {
                // 进入循环时，确保了 cur 不会与上一节点相同
                if (cur.next == null || cur.val != cur.next.val) {
                    prev.next = cur;
                    prev = cur;
                }
                // 如果 cur 与下一节点相同，跳过相同节点
                while (cur.next != null && cur.val == cur.next.val) {
                    cur = cur.next;
                }
                cur = cur.next;
            }
            prev.next = null;
            return dummy.next;
        }
    }
}